from PIL import Image
import xml.etree.ElementTree as ET
from PIL import Image
from pathlib import Path

if __name__ == "__main__":
    image_paths = Path("/home/luoluoluo/data/dataset/大厅/images")
    xml_paths = image_paths.parent / "Annotations"

    for i, img_path in enumerate(image_paths.glob('*.jpg')):
        xml_path = str(xml_paths / img_path.stem) + ".xml"  #获取jpg图片对应的xml标签

        # 解析XML文件
        tree = ET.parse(xml_path)
        root = tree.getroot()

        # 图像路径
        image = Image.open(img_path)
        j = 0

        # 遍历所有名为"person"的对象
        for obj in root.findall('.//object'):
            
            name = obj.find('name').text
            if name == 'person':
                bndbox = obj.find('bndbox')
                xmin = int(bndbox.find('xmin').text)
                ymin = int(bndbox.find('ymin').text)
                xmax = int(bndbox.find('xmax').text)
                ymax = int(bndbox.find('ymax').text)
                if (xmax - xmin) + (ymax - ymin) < 350:
                    continue
                # 截取图像
                person_image = image.crop((xmin, ymin, xmax, ymax))
                
                # 保存截取的物体图像，你可以更改文件名
                person_image.save(f'./output/{name}_{i+12}_{j}.jpg')
                j += 1

